import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'

import { Modal, NavBar, Swiper, Toast } from 'antd-mobile'

import HousePackage from '../../components/HousePackage'

import { API, BASE_URL, isAuth } from '../../utils'

import styles from './index.module.css'

const BMapGL = window.BMapGL
// 覆盖物样式
const labelStyle = {
  cursor: 'pointer',
  border: '0px solid rgb(255, 0, 0)',
  padding: '0px',
  whiteSpace: 'nowrap',
  fontSize: '14px',
  color: 'rgb(255, 255, 255)',
  textAlign: 'center'
}

const obj = {
  houseImg: [],
  title: '',
  tags: [],
  price: 0,
  // 房型
  roomType: '',
  // 房屋面积
  size: 0,
  // 朝向
  oriented: [],
  // 楼层
  floor: '',
  // 小区名称
  community: '',
  // 地理位置
  coord: {
    latitude: '39.928033',
    longitude: '116.529466'
  },
  // 房屋配套
  supporting: [],
  // 房屋标识
  houseCode: '',
  // 房屋描述
  description: ''
}

export default function HouseDetail({ history, location }) {
  // 房屋详情
  const [houseInfo, setHouseInfo] = useState(obj)
  // 表示房源是否收藏
  const [isFavorite, setIsFavorite] = useState(false)
  // 路由参数 id
  const { id } = useParams()

  // 获取房源详情信息
  useEffect(() => {
    // 回到顶部
    window.scrollTo(0, 0)

    const getHouseInfo = async () => {
      const { data: res } = await API.get(`/houses/${id}`)
      setHouseInfo(res.body)
      const { community, coord } = res.body
      renderMap(community, coord)
    }

    getHouseInfo()
  }, [id])

  // 获取收藏状态
  useEffect(() => {
    const checkFavorite = async () => {
      const isLogin = isAuth()

      // 没有登录
      if (!isLogin) return

      // 已登录
      const { data: res } = await API.get(`/user/favorites/${id}`)
      console.log(res)
      // 请求失败
      if (res.status !== 200) return

      // 请求成功
      setIsFavorite(res.body.isFavorite)
    }

    checkFavorite()
  }, [id])

  const handleFavorite = async () => {
    const isLogin = isAuth()

    // 未登录
    if (!isLogin) {
      const result = await Modal.confirm({
        title: '提示',
        content: '登录后才能收藏房源，是否去登录？'
      })

      // 取消
      if (!result) return

      // 确定
      history.push('/login', { from: location })
      return
    }

    if (isFavorite) {
      // 已收藏，应该删除收藏
      const { data: res } = await API.delete(`/user/favorites/${id}`)
      setIsFavorite(false)
      if (res.status === 200) {
        // 提醒用户取消收藏
        Toast.show({ content: '已取消收藏' })
      } else {
        Toast.show({ content: '登录超时，请重新登录' })
      }
    } else {
      // 未收藏，应该添加收藏
      const { data: res } = await API.post(`/user/favorites/${id}`)
      if (res.status === 200) {
        // 提醒用户收藏成功
        Toast.show({ content: '已收藏' })
        setIsFavorite(true)
      } else {
        Toast.show({ content: '登录超时，请重新登录' })
      }
    }
  }

  // 渲染轮播图组件
  const renderSwipers = () => {
    if (!houseInfo.houseImg.length) return null

    const { houseImg } = houseInfo
    return (
      <Swiper loop>
        {houseImg.map((item, i) => (
          <Swiper.Item key={i}>
            <img src={BASE_URL + item} alt="" />
          </Swiper.Item>
        ))}
      </Swiper>
    )
  }

  // 渲染地图
  const renderMap = (community, coord) => {
    const { longitude, latitude } = coord
    const map = new BMapGL.Map('map')
    const point = new BMapGL.Point(longitude, latitude)
    map.centerAndZoom(point, 17)
    // 添加缩放控件
    map.addControl(new BMapGL.ZoomControl())

    // 创建覆盖物
    const label = new BMapGL.Label('', {
      position: point,
      offset: new BMapGL.Size(0, 0)
    })

    // 设置房源覆盖物内容
    label.setContent(`
      <div class="${styles.rect}">
        <span class="${styles.houseName}">${community}</span>
        <i class="${styles.arrow}"></i>
      </div>
    `)

    // 设置样式
    label.setStyle(labelStyle)

    // 添加覆盖物到地图中
    map.addOverlay(label)
  }

  // 渲染标签
  const renderTags = () => {
    const { tags } = houseInfo

    return tags.map((tag, i) => {
      let tagClass = ''
      if (i > 2) {
        tagClass = 'tag3'
      } else {
        tagClass = 'tag' + (i + 1)
      }
      return (
        <span key={i} className={[styles.tag, styles[tagClass]].join(' ')}>
          {tag}
        </span>
      )
    })
  }

  const { community, title, price, roomType, size, floor, oriented, supporting, description } =
    houseInfo

  return (
    <div className={styles.root}>
      {/* 导航 */}
      <NavBar right={<i className="iconfont icon-share" />} onBack={() => history.go(-1)}>
        {community}
      </NavBar>

      {/* 轮播图 */}
      <div className={styles.slides}>{renderSwipers()}</div>

      {/* 房屋基本信息 */}
      <div className={styles.info}>
        {/* 标题信息 */}
        <h3 className={styles.infoTitle}>{title}</h3>
        {/* 标签信息 */}
        <div className={[styles.infoTags, styles.flex].join(' ')}>
          <div className={styles.tags}>{renderTags()}</div>
        </div>

        {/* 房屋基本信息 */}
        <div className={[styles.infoPrice, styles.flex].join(' ')}>
          <div className={styles.infoPriceItem}>
            <div>
              {price}
              <span className={styles.month}>/月</span>
            </div>
            <div>租金</div>
          </div>
          <div className={styles.infoPriceItem}>
            <div>{roomType}</div>
            <div>房型</div>
          </div>
          <div className={styles.infoPriceItem}>
            <div>{size}平方</div>
            <div>面积</div>
          </div>
        </div>

        {/* 基本情况 */}
        <div className={[styles.infoBasic, styles.flex].join(' ')}>
          <div>
            <div>
              <span className={styles.title}>装修：</span>
              精装
            </div>
            <div>
              <span className={styles.title}>楼层：</span>
              {floor}
            </div>
          </div>
          <div>
            <div>
              <span className={styles.title}>朝向：</span>
              {oriented.join('、')}
            </div>
            <div>
              <span className={styles.title}>类型：</span>
              普通住宅
            </div>
          </div>
        </div>
      </div>

      {/* 地图位置 */}
      <div className={styles.map}>
        <div className={styles.mapTitle}>小区：{community}</div>
        <div className={styles.mapContainer} id="map"></div>
      </div>

      {/* 房屋配套 */}
      <div className={styles.about}>
        <div className={styles.houseTitle}>房屋配套</div>
        {supporting.length ? (
          <HousePackage list={supporting} />
        ) : (
          <div className={styles.titleEmpty}>暂无数据</div>
        )}
      </div>

      {/* 房屋概况 */}
      <div className={styles.set}>
        <div className={styles.houseTitle}>房屋概况</div>
        <div>
          <div className={styles.contact}>
            <div className={styles.user}>
              <img src={BASE_URL + '/img/avatar.png'} alt="头像" />
              <div className={styles.userInfo}>
                <div>张女士</div>
                <div className={styles.userAuth}>
                  <i className="iconfont icon-auth" />
                  已认证房主
                </div>
              </div>
            </div>
            <span className={styles.userMsg}>发消息</span>
          </div>
          <div className={styles.descText}>{description ? description : '暂无房屋数据'}</div>
        </div>
      </div>

      {/* 底部按钮 */}
      <div className={styles.buttons}>
        <span className={styles.favorite} onClick={handleFavorite}>
          <img
            src={BASE_URL + (isFavorite ? '/img/star.png' : '/img/unstar.png')}
            alt={isFavorite ? '已收藏' : '收藏'}
          />
          {isFavorite ? '已收藏' : '收藏'}
        </span>
        <span className={styles.consult}>在线咨询</span>
        <span className={styles.reserve}>
          <a href="tel: 183614999905">电话预定</a>
        </span>
      </div>
    </div>
  )
}
